from docx import Document
import re
import os

from docx import Document
import os

def split_by_h1(input_path, output_folder):
    """
    根据Word中的H1标题分割文档，并保留所有格式
    :param input_path: 输入Word文件路径
    :param output_folder: 分割后文件保存目录
    """
    os.makedirs(output_folder, exist_ok=True)
    doc = Document(input_path)
    sections = []
    current_section = []

    # 分割逻辑（保留所有段落对象）
    for paragraph in doc.paragraphs:
        if paragraph.style.name == 'Heading 1':
            if current_section:
                sections.append(current_section)
                current_section = []
        current_section.append(paragraph)  # 始终添加当前段落（包括H1标题）

    if current_section:
        sections.append(current_section)

    # 保存时复制所有格式
    for i, section in enumerate(sections, 1):
        new_doc = Document()
        for paragraph in section:
            # 复制整个段落对象（包含格式）
            new_p = new_doc.add_paragraph(style=paragraph.style)
            for run in paragraph.runs:
                # 复制run级别的格式（字体、加粗等）
                new_run = new_p.add_run(run.text)
                new_run.bold = run.bold
                new_run.italic = run.italic
                new_run.underline = run.underline
                new_run.font.color.rgb = run.font.color.rgb
                new_run.font.name = run.font.name
                new_run.font.size = run.font.size

        # 保存文件
        output_path = os.path.join(output_folder, f"Chapter_{i}.docx")
        new_doc.save(output_path)
        print(f"已保存（保留格式）: {output_path}")









# 使用示例（绝对路径或相对路径均可）
split_by_h1(
    input_path="E:\learn-document\日语学习\标准日语语法汇总.docx",
    output_folder="output_chapters"  # ← 修改为你需要的实际路径
)
